package cn.iocoder.yudao.module.picturebook.controller.admin.bigplan;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.picturebook.controller.admin.bigplan.vo.*;
import cn.iocoder.yudao.module.picturebook.service.bigplan.BigplanService;

@Tag(name = "绘本系统 - 大计划表	")
@RestController
@RequestMapping("/picturebook/bigplan")
@Validated
public class BigplanController {

    @Resource
    private BigplanService bigplanService;

    @PostMapping("/create")
    @Operation(summary = "创建大计划表	")
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:create')")
    public CommonResult<Integer> createBigplan(@Valid @RequestBody BigplanSaveReqVO createReqVO, @RequestHeader("token") Integer userId) {
        return success(bigplanService.createBigplan(createReqVO, userId));
    }

    @PutMapping("/update")
    @Operation(summary = "更新大计划表(暂不使用)	")
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:update')")
    public CommonResult<Boolean> updateBigplan(@Valid @RequestBody BigplanSaveReqVO updateReqVO) {
        bigplanService.updateBigplan(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除大计划表	")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:delete')")
    public CommonResult<Boolean> deleteBigplan(@RequestParam("id") Integer id) {
        bigplanService.deleteBigplan(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除大计划表(暂不使用)	")
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:delete')")
    public CommonResult<Boolean> deleteBigplanList(@RequestParam("ids") List<Integer> ids) {
        bigplanService.deleteBigplanListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得大计划表	")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:query')")
    public CommonResult<List<BigplanRespVO>> getBigplan(@RequestParam("id") Integer id) {
        return success(bigplanService.getBigplan(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得大计划表分页(暂不使用)")
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:query')")
    public CommonResult<PageResult<BigplanRespVO>> getBigplanPage(@Valid BigplanPageReqVO pageReqVO) {
        bigplanService.getBigplanPage(pageReqVO);
        return null;
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出大计划表	 Excel")
    @PreAuthorize("@ss.hasPermission('picturebook:bigplan:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBigplanExcel(@Valid BigplanPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<BigplanRespVO> list = bigplanService.getBigplanPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "大计划表	.xls", "数据", BigplanRespVO.class,
                BeanUtils.toBean(list, BigplanRespVO.class));
    }

    @GetMapping("/getDayPlan")
    @Operation(summary = "获取用户当天的所有计划")
    public CommonResult<List<BigplanTodayRespVO>> getDayPlan(@RequestHeader("token") Integer userId) {
        // 校验 userId 合法性
        if (userId == null || userId <= 0) {
            return CommonResult.error(303, "用户ID无效");
        }

        CommonResult<List<BigplanTodayRespVO>> dayPlan = bigplanService.getDayPlan(userId);

        // 判断服务调用是否成功
        if (!dayPlan.isSuccess()) {
            return dayPlan; // 直接返回原始错误结果
        }

        List<BigplanTodayRespVO> result = new ArrayList<>();
        if (dayPlan.getData() != null) {
            result = dayPlan.getData().stream()
                    .filter(vo -> vo.getPlanContent() != null && !vo.getPlanContent().isEmpty())
                    .collect(Collectors.toList());
        }
        //判断当前是计划的第几天
        //获取当前时间和任务创建时间
        //循环任务
        LocalDateTime now = LocalDateTime.now();
        for (BigplanTodayRespVO todayRespVO : result) {
            todayRespVO.setPlanDay(now.getDayOfYear() - todayRespVO.getCreateTime().getDayOfYear() + 1);
        }
        return CommonResult.success(result);
    }
    //新增绘本集计划
    @PostMapping("/addBigplanGather")
    @Operation(summary = "新增绘本集计划")
    public CommonResult<Boolean> addBigplanGather(@Validated @RequestBody BigplanGatherRespVO reqVO, @RequestHeader("token") Integer userId) {
        return success(bigplanService.addBigplanGather(reqVO, userId));
    }
}